package rmiServeur;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.Random;

import interfaces.Client_ITF;
import interfaces.Serveur_ITF;

public class Serveur_IMPL extends UnicastRemoteObject implements Serveur_ITF {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	ArrayList<Client_ITF> clients;

	public Serveur_IMPL() throws RemoteException {
		super();
		clients = new ArrayList<Client_ITF>();
	}

	@Override
	public void addClient(Client_ITF c) throws RemoteException {
		System.out.println("addClient :" + c);
		clients.add(c);
	}

	@Override
	public ArrayList<Client_ITF> getNeighbors(Client_ITF client)
			throws RemoteException {
		System.out.println("getneigbors pour le client :" + client);
		// Initialisation of the neighborsList
		ArrayList<Client_ITF> result = new ArrayList<Client_ITF>();

		int clientIndex = clients.indexOf(client);

		// if there is one or two other clients registered we put all of them as
		// neighbors
		if (clients.size() > 1 && clients.size() < 4) {
			for (int i = 0; i < clients.size(); i++) {
				if (i != clientIndex) {
					result.add(clients.get(i));
				}
			}

		} else if (clients.size() > 3) {
			// if there is more than two other clients we choose randomly two of
			// them
			Random r = new Random();
			int newNeighborIndex;
			while (result.size() < 2) {
				newNeighborIndex = r.nextInt(clients.size());

				// We check that we doesn't choice randomly the requesting
				// client itself
				if (newNeighborIndex != clientIndex
						&& !result.contains(clients.get(newNeighborIndex))) {
					System.out.println("client num : " + clientIndex
							+ "\tvoisin : " + newNeighborIndex);
					result.add(clients.get(newNeighborIndex));
				}
			}
		}

		// for each chosen client we add them a new neighbors (the requesting
		// client)
		for (Client_ITF newNeighbor : result) {
			System.out.println("on ajoute le nouveau voisin" + client + " à :"
					+ newNeighbor);
			try {
				newNeighbor.addNeighbor(client);
			} catch (RemoteException e) {
				System.err.println("L'ajout au client " + newNeighbor
						+ " le voisin " + client + " à échoué");
			}
			System.out.println("Nombre de voisin de" + newNeighbor + " :"
					+ newNeighbor.getNeighbors().size());
		}

		return result;
	}

	@Override
	public void removeClient(Client_ITF client) throws RemoteException {
		System.out.println("remove client from :" + client);
		clients.remove(client);

		for (Client_ITF neighborOfOldClient : client.getNeighbors()) {
			neighborOfOldClient.removeNeighbor(client);
		}

	}

}
